#!/usr/bin/python
# -*- coding: utf-8 -*-
######################################
# File name : main.py
# Create date : 2019-10-20 19:37
# Modified date : 2020-04-01 23:11
# Author : liuzy
# Describe : not set
# Email : lzygzh@126.com
######################################
import os
import time

from MoZiAI_SDK.examples.Iraq_learn.env import IraqEnv as Environment
from MoZiAI_SDK.examples.Iraq_learn import etc
from MoZiAI_SDK.examples.Iraq_learn.agent import Agent

import psutil

def main():
    # 判断墨子是否已经启动
    PROCESS_NAME = "MoziServer.exe"
    p_state=False

    for i in psutil.process_iter():
        if i.name() == PROCESS_NAME:
            str_tmp = str(i.name()) + "-" + str(i.pid) + "-" + str(i.status())
            print("墨子已启动:"+str_tmp)
            p_state=True
            break
	# 启动墨子
    if p_state==False:
        mozi_path = os.environ['MOZIPATH']
        mozi_p=mozi_path + '\MoziServer.exe'
        os.popen(mozi_p)
        time.sleep(30)

    #创建环境对象
    env = Environment(etc.SERVER_IP, etc.SERVER_PORT, etc.SCENARIO_NAME, etc.simulate_compression, etc.DURATION_INTERVAL)
    #启动环境
    env.start()
    #创建智能体对象
    agent = Agent(env)

    try:
        for _ep in range(0, etc.MAX_EPISODES):
            #设置智能体
            agent.setup(env.observation_space, env.action_space)
            #重置环境
            timesteps = env.reset()
            #重置智能体
            agent.reset()
            for step in range(etc.MAX_STEPS):
                #运行一步
                timesteps = agent.step(timesteps[0])
                print(timesteps)
                if timesteps[2]:
                    break

    except KeyboardInterrupt:
        pass

main()
